<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/4/28
 * Time: 9:34
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use app\common\model\Department as depart;
use nx\Data;
use think\Db;

class Department extends Admin
{
    public function index()
    {
        $depart = new depart();
        $data = $depart->order('id')->select();
        $data = $data->toArray();
        $data=Data::tree($data,'sectionname','id','fid');
        $this->assign('depardata',$data);
        return $this->fetch();
    }
    //添加菜单
    public function add(){
        if($this->request->isPost()){
            $menu = new depart();
            $data=input('post.');
            if($data['fid']!=0){
                $str = Db::where(['fid'=>$data['fid']])->field('path');
                $data['path'] = $str.$data['fid'];
            }
            $result=$menu->validate(TRUE)->save($data);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }else{
                $this->success('添加成功！');
            }
        } else {
            $pid= $this->request->param('id');
            $this->assign('fid',$pid);
            return $this->fetch('edit');
        }
    }
    //编辑菜单
    public function edit(){
        $menu = new depart;
        if($this->request->isPost()){
            $data=input('post.');
//            halt($data['fid']!=0);
            if($data['fid']!=0){
                $str = Db::name('department')->where(['id'=>$data['fid']])->field('path')->find();
                $data['path'] = $str['path'].'-'.$data['fid'];
            }

            $result=$menu->validate(TRUE)->isUpdate(TRUE)->save($data);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($menu->getError());
            }else{
                $this->success('更新成功！');
            }
        } else {
            $pid= $this->request->param('id');
            $info=$menu->where(['id'=>$pid])->find();
            $this->assign('info',$info);
            $this->assign('fid',$info['fid']);
            return $this->fetch('edit');
        }
    }
    //删除菜单
    public function del(){
        $id = $this->request->param('id',0);
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        if(Db::name('department')->where('fid',$id)->find()){
            $this->error('该部门有子部门不能删除!');
        }else{
            if(depart::destroy($id)){
                $this->success('删除成功');
            } else {
                $this->error('删除失败!');
            }
        }
    }
}